<template>
  <div class="op-container">
    <hq-searchDown ref="hqSearchDown" :select-opts="selectOpts" @click="handleFilter" />
    <div class="filter-container">
      <span class="filter-title filter-item">注册时间</span>
      <k-date-picker v-model="timeValue" class="filter-item" @hqchang="$refs.hqSearchDown.searchFun()" />
      <!-- <k-input
        v-model.trim="listQuery.key"
        class="filter-item"
        is-search
        placeholder="请输入关键词"
        :search-fun="handleFilter"
        @keyup.enter.native="handleFilter"
      /> -->
    </div>
    <!-- openAssignAccountDialog -->
    <k-button v-if="authorityHandle(22)" class="top-btn" value="分配账号" @click.native="openAssignAccountDialog" />
    <div style="margin-top: 40px;" />
    <!--表格相关 -->
    <el-table
      :key="1"
      :data="listData"
      fit
      border
      highlight-current-row
      style="width: 100%;border-radius:8px;"
      :header-cell-style="{ background: '#F6F5FA', color: '#4E4F62' }"
    >
      <el-table-column width="60px" label="序号" type="index" align="center" show-overflo-tooltips />
      <el-table-column prop="nickName" min-width="200px" label="昵称" align="center" show-overflo-tooltips />
      <el-table-column prop="mobile" min-width="200px" label="用户名" align="center" show-overflo-tooltips />
      <el-table-column prop="adminRoleName" min-width="200px" label="所属角色" align="center" show-overflo-tooltips />
      <el-table-column prop="adminUserMobile" min-width="200px" label="绑定手机号" align="center" show-overflo-tooltips />
      <el-table-column prop="createTime" min-width="200px" label="分配时间" align="center" show-overflo-tooltips />
      <el-table-column prop="creatorName" min-width="200px" label="创建人" align="center" show-overflo-tooltips />
      <el-table-column prop="userStatusName" min-width="200px" label="账号状态" align="center" show-overflo-tooltips />
      <el-table-column v-if="authorityHandle(22)" min-width="120px" label="设备限制" align="center" show-overflo-tooltips>
        <template slot-scope="{ row }">
          <div class="finger-container">
            <editable-cell
              v-model="row.fingerprintCount"
              :show-input="row.editMode"
              @keyup.enter.native="upDateFingerCount(row)"
            >
              <span slot="content" class="content">{{ row.fingerprintCount }}</span>
            </editable-cell>
            <p class="finger-delete" @click="clearFinger(row)">清空</p>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        v-else
        prop="fingerprintCount"
        min-width="160px"
        label="设备限制"
        align="center"
        show-overflo-tooltips
      />
      <el-table-column
        v-if="authorityHandle(22)"
        fixed="right"
        min-width="300px"
        label="操作"
        align="center"
        show-overflo-tooltips
      >
        <template slot-scope="scope">
          <div class="op-div">
            <k-button class="table-btn" value="修改" @click.native="userUpdateDialog(scope.row)" />
            <k-button
              class="table-btn"
              :value="scope.row.userStatusInt === 0 ? '解封' : '冻结'"
              @click.native="updateStatus(scope.row)"
            />
            <!-- <k-button class="table-btn" value="清空指纹" @click.native="clearFinger(scope.row)" /> -->
          </div>
        </template>
      </el-table-column>

      <el-table-column v-else width="1px" label="" align="center" style="opacity: 0;">
        <template>
          <div class="op-div" />
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="totalRows > 0"
      :total="totalRows"
      :page.sync="listQuery.pager.pageNo"
      :limit.sync="listQuery.pager.pageSize"
      @pagination="$refs.hqSearchDown.searchFun(1)"
    />
    <!-- 分配账号 弹窗 -->
    <k-dialog
      :show-hide.sync="openAssignAccount.showHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      :title="textMap[dialogStatus]"
      :show-foot="false"
      :two-btn="true"
      :close-fun="closeFun"
      @click="assignAccount"
    >
      <el-form ref="formName" :model="adminuserinfo" label-width="auto" :rules="adminrules" class="form-modify">
        <el-form-item label="所属角色：">
          <el-select v-model="adminuserinfo.adminRoleId" placeholder="请选择">
            <el-option v-for="item in allRoleData" :key="item.id" :label="item.roleName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="昵称：" prop="nickName"><el-input
          v-model="adminuserinfo.nickName"
          placeholder="建议使用用户的真实姓名"
        /></el-form-item>
        <el-form-item label="用户名：" prop="mobile"><el-input
          v-model="adminuserinfo.mobile"
          placeholder="建议使用字母+数字的8位组合"
        /></el-form-item>
        <el-form-item label="密码：" prop="password"><el-input
          v-model="adminuserinfo.password"
          show-password
          placeholder="建议使用字母+数字的8位组合"
        /></el-form-item>
        <el-form-item label="绑定手机号：" prop="adminUserMobile"><el-input
          v-model="adminuserinfo.adminUserMobile"
          placeholder="接收手机验证码"
        /></el-form-item>
      </el-form>
    </k-dialog>
  </div>
</template>

<script>
import { listData, update, save, updateStatus, allRole, clearFingerprint, setFingerprintCount } from '@/api/user/user'
import Pagination from '@/components/Pagination'
import hqSearchDown from '@/components/hqSearchDown' // 下拉搜索
import EditableCell from '@/components/EditableCell'

export default {
  components: { Pagination, hqSearchDown, EditableCell },
  data() {
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('绑定手机号不能为空'))
      }
      // 使用正则表达式进行验证绑定手机号码
      if (!/^1[3456789]\d{9}$/.test(value)) {
        callback(new Error('绑定手机号格式不正确'))
      }
      // 自定义校验规则 需要调用callback()函数！
      callback()
    }
    return {
      // 下拉搜索项0
      selectOpts: [
        {
          label: '手机号',
          rigth: true,
          value: 'adminUserMobile'
        },
        {
          label: '关键词',
          rigth: true,
          value: 'key'
        }
      ],
      allRoleData: [], // 所属角色 -- 全部角色
      dialogStatus: 'create',
      textMap: {
        update: '修改',
        create: '分配账号'
      },
      listData: [],
      totalRows: 0, // 分页组件--数据总条数
      listQuery: {
        pager: {
          pageNo: 1,
          pageSize: 10,
          totalRows: '',
          start: ''
        },
        sort: '', // 排序字段 为对应列名,
        direction: '', // 排序 正向(asc)逆向(desc),
        roleId: 1, // 用户角色-AI",
        nickName: undefined, // 昵称",
        userIdStatus: undefined, // 在线状态",
        userStatus: '', // 账号状态",
        startTime: '', // 开始时间",
        endTime: '', // 结束时间",
        key: '' // 饰品名称'
      },
      adminuserinfo: {
        id: undefined,
        roleId: 1,
        mobile: '',
        password: '',
        nickName: '',
        adminRoleId: '',
        adminUserMobile: ''
      },
      adminrules: {
        nickName: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        adminUserMobile: [{ required: true, validator: validatePhone, trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入用户名', trigger: 'blur' }]
      },
      timeValue: '',
      paramData: {},
      openAssignAccount: {
        showHide: false
      }
    }
  },
  watch: {
    // 时间赋值
    timeValue(val) {
      this.listQuery.startTime = this.timeValue ? this.timeValue[0] : null
      this.listQuery.endTime = this.timeValue ? this.timeValue[1] : null
    }
  },
  created() {
    this.loadData()
  },
  beforeDestroy() {
    localStorage.setItem('pagination', '1')
  },
  methods: {
    upDateFingerCount(row) {
      setFingerprintCount({
        userId: row.id,
        fingerprintCount: row.fingerprintCount
      }).then(res => {
        this.$message.success(res.message)
      })
    },
    clearFinger(row) {
      this.$confirm('确定要清除该用户所有的设备指纹标识么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          clearFingerprint({
            userId: row.id
          }).then(res => {
            this.$message.success(res.message)
          })
        })
        .catch(() => { })
    },
    loadData(val) {
      if (val) {
        localStorage.setItem('pagination', val.page)
      }
      this.paramData = {}
      this.paramData = { ...this.listQuery, ...val }
      listData(this.paramData).then(res => {
        this.$log(res)
        const data = res.data
        if (data.rows) {
          this.listData = data.rows.map(row => {
            return {
              ...row,
              editMode: false
            }
          })
        } else {
          this.listData = []
        }
        this.totalRows = data.totalRows
      })
    },
    // 分配账号
    assignAccount() {
      this.$refs.formName.validate(valid => {
        if (valid) {
          if (this.dialogStatus === 'update') {
            update(this.adminuserinfo).then(res => {
              if (res.data.success) {
                this.handlePageFilter()
                this.$message.success('修改成功')
                this.$resetForm(this.adminuserinfo)
                this.openAssignAccount.showHide = false
              } else {
                this.$message.error(res.data.msg)
              }
            })
          } else {
            save(this.adminuserinfo).then(res => {
              if (res.data.success) {
                this.handleFilter()
                this.$message.success('分配成功')
                this.$resetForm(this.adminuserinfo)
                this.openAssignAccount.showHide = false
              } else {
                this.$message.error(res.data.msg)
              }
            })
          }
        }
      })
    },
    closeFun() {
      this.$refs.formName.resetFields()
      this.$resetForm(this.adminuserinfo)
    },
    // 修改账号状态
    updateStatus(row) {
      if(row.id ==this.$store.state.user.id)return this.$message.warning('此用户为当前用户!');
      updateStatus({ userId: row.id, userStatus: row.userStatusInt === 0 ? 1 : 0 }).then(res => {
        this.$log(res)
        if (res.data.success) {
          this.handlePageFilter()
          this.$message.success('操作成功')
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },
    userUpdateDialog(row) {
      this.dialogStatus = 'update'
      this.adminuserinfo.id = row.id
      this.adminuserinfo.roleId = 1
      this.adminuserinfo.mobile = row.mobile
      this.adminuserinfo.password = row.showPassword
      this.adminuserinfo.nickName = row.nickName
      this.adminuserinfo.adminRoleId = row.adminRoleId
      this.adminuserinfo.adminUserMobile = row.adminUserMobile
      allRole().then(res => {
        this.allRoleData = res.data
        this.openAssignAccount.showHide = true
      })
    },
    handlePageFilter() {
      this.listQuery.pager.pageNo = Number(localStorage.getItem('pagination')) || 1
      this.$refs.hqSearchDown.searchFun(1)
    },
    // 搜索查询事件
    // 搜索查询事件
    handleFilter(v, type) {
      if (type !== 1) this.listQuery.pager.pageNo = 1
      else localStorage.setItem('pagination', this.listQuery.pager.pageNo)
      this.loadData(v)
    },
    openAssignAccountDialog() {
      this.adminuserinfo.roleId = 1
      this.dialogStatus = 'create'
      allRole().then(res => {
        this.allRoleData = res.data
        this.openAssignAccount.showHide = true
      })
    }
  }
}
</script>
<style lang="scss" scoped>
$menuText: #14162e; // 侧边栏字体颜色
$hoverColor: #1D143C; // 鼠标停留主色调浅色
$mainColor: #3b425d; // 主色调

.op-container {
  margin: 20px;
}

.filter-container {
  width: 100%;
  height: 48px;
  line-height: 48px;

  .filter-item {
    display: inline-block;
    vertical-align: middle;
    margin-bottom: 10px;
  }

  .kInput {
    position: absolute;
    right: 20px;
  }

  .filter-title {
    height: 48px;
    line-height: 48px;
    font-size: 16px;
    font-weight: 500;
    margin-right: 22px;
    color: #14162e;
  }

  .user-item {
    margin-left: 10px;
    margin-right: 20px;
  }

  .user-status,
  .account-status {
    margin-right: 20px;
  }
}

.top-btn {
  margin: 30px 0px 30px 0px;
  font-size: 14px;
  color: #ffffff;
}

::v-deep .el-input__inner:focus {
  border-color: $mainColor;
}

.el-form-item__label-wrap .el-form-item__label {
  float: none;
}

.dialog-openboxsetting {
  display: flex;
  flex-direction: row;
  justify-content: center;
  margin: 80px 80px;
}

.form-modify {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  margin: 10px 80px;

  .modify-right {
    margin-left: 80px;
  }

  ::v-deep .el-input__inner {
    border-color: $mainColor;
    width: 200px;
  }
}

.finger-container {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;

  .content {
    display: inline-block;
    width: 60px;
    height: 50px;
    line-height: 50px;
  }

  .finger-delete {
    width: 40px;
    color: #3b425d;
    font-size: 14px;
    cursor: pointer;
  }
}
</style>
